<template>
  <a-card class="editor-card">
    <template #title>
      <div class="editor-header">
        <a-select v-model:value="selectedLanguage" style="width: 120px">
          <a-select-option v-for="lang in validLanguages" :key="lang.value" :value="lang.value">
            {{ lang.label }}
          </a-select-option>
        </a-select>
        <div class="editor-actions">
          <a-button @click="handleReset">
            <template #icon>
              <redo-outlined/>
            </template>
            重置
          </a-button>
          <a-button @click="handleSave">
            <template #icon>
              <save-outlined/>
            </template>
            保存
          </a-button>
          <a-button type="default" class="yellow-btn" :disabled="isTestsubmitting || isSubmitsubmitting" :loading="isTestsubmitting" @click="handleTest">
            <template #icon>
              <InfoCircleOutlined/>
            </template>
            测试
          </a-button>
          <a-button type="primary" :disabled="isTestsubmitting || isSubmitsubmitting"  :loading="isSubmitsubmitting" @click="handleSubmit">
            <template #icon>
              <check-outlined/>
            </template>
            提交
          </a-button>
          <a-tooltip title="[测试]仅进行单用例测试，不计入提交记录。[提交]会计入总成绩">
            <question-circle-outlined style="margin-right: 8px; color: #8c8c8c"/>
          </a-tooltip>
        </div>
      </div>
    </template>
    <div class="editor-container" @click="handleEditorContainerClick">
      <Codemirror
          v-model:value="code"
          :options="cmOptions"
          border
          placeholder="请在此处编写代码..."
          :height="600"
          @change="change"
          @ready="onCmReady"
      />

      <!-- 提交简单测试结果 Drawer -->
      <div v-if="showTestResult" class="result-drawer" @click.stop>
        <div class="result-drawer-header">
          <div class="result-header">
            <span>测试结果</span>
            <a-tag style="margin: 0" :color="getStatusTag(submissionResult.status).color">
              {{ getStatusTag(submissionResult.status).text }}
            </a-tag>
          </div>
        </div>
        <div class="result-drawer-body">
          <div class="result-content">
            <div class="result-item">
              <span class="label">执行用时：</span>
              <span class="value">{{ submissionResult.executionTime }}</span>
              <span class="label" style="margin-left: 20px">内存消耗：</span>
              <span class="value">{{ submissionResult.memoryUsage }}</span>
            </div>

            <!-- 显示编译错误 -->
            <div v-if="submissionResult.status === 'compile_error' && submissionResult.stderr"
                 class="error-message">
              <div class="error-title">编译错误：</div>
              <pre class="error-content">{{ submissionResult.stderr }}</pre>
            </div>

            <!-- 显示运行时错误 -->
            <div v-else-if="submissionResult.status === 'runtime_error' && submissionResult.stderr"
                 class="error-message">
              <div class="error-title">运行时错误：</div>
              <pre class="error-content">{{ submissionResult.stderr }}</pre>
            </div>

            <!-- 显示答案错误 -->
            <div v-else-if="submissionResult.status === 'wrong_answer'" class="testcase-result">
              <div class="testcase-header">测试用例结果：</div>
              <div class="testcase-item">
                <div class="testcase-title">输入：</div>
                <pre class="testcase-content">{{ submissionResult.userInput }}</pre>
              </div>
              <div class="testcase-item">
                <div class="testcase-title">期望输出：</div>
                <pre class="testcase-content">{{ submissionResult.expectedOutput }}</pre>
              </div>
              <div class="testcase-item">
                <div class="testcase-title">实际输出：</div>
                <pre class="testcase-content">{{ submissionResult.userOutput }}</pre>
              </div>
            </div>

            <!-- 通过 -->
            <div v-else-if="submissionResult.status === 'passed'" class="success-message">
              <div class="success-title">恭喜！您的代码通过了测试。</div>
              <div class="testcase-item">
                <div class="testcase-title">输入：</div>
                <pre class="testcase-content">{{ submissionResult.userInput }}</pre>
              </div>
              <div class="testcase-item">
                <div class="testcase-title">输出：</div>
                <pre class="testcase-content">{{ submissionResult.userOutput }}</pre>
              </div>
            </div>
            
            <!-- 其他错误 -->
            <div v-else-if="submissionResult.stderr" class="error-message">
              <div class="error-title">错误信息：</div>
              <pre class="error-content">{{ submissionResult.stderr }}</pre>
            </div>
          </div>
        </div>
      </div>

      <!-- 提交正式评测结果 Drawer -->
      <div v-if="showSubmitResult" class="result-drawer submit-result-drawer" @click.stop>
        <div class="result-drawer-header"
             :class="{'success-header': judgeResult?.submission?.status === 0, 'error-header': judgeResult?.submission?.status !== 0}">
          <div class="result-header">
            <span>提交结果</span>
            <a-tag :color="judgeResult?.submission?.status === 0 ? 'success' : 'error'">
              {{ getJudgeStatusText(judgeResult?.submission?.status) }}
            </a-tag>
          </div>
        </div>
        <div class="result-drawer-body"
             :class="{'success-body': judgeResult?.submission?.status === 0, 'error-body': judgeResult?.submission?.status !== 0}">
          <div class="result-content">
            <div class="result-item">
              <span class="label">执行用时：</span>
              <span class="value">{{ judgeResult?.submission?.time }}ms</span>
              <span class="label" style="margin-left: 20px">内存消耗：</span>
              <span class="value">{{ formatMemory(judgeResult?.submission?.memory) }}</span>
            </div>
            <div class="result-item">
              <span class="label">题目编号：</span>
              <span class="value">{{ judgeResult?.submission?.displayPid }}</span>
              <span class="label" style="margin-left: 20px">评测机：</span>
              <span class="value">{{ judgeResult?.submission?.judger }}</span>
            </div>
            <div class="result-item">
              <span class="label">提交时间：</span>
              <span class="value">{{ formatDate(judgeResult?.submission?.submitTime) }}</span>
              <span class="label" style="margin-left: 20px">代码长度：</span>
              <span class="value">{{ judgeResult?.submission?.length }} 字符</span>
            </div>

            <!-- 错误信息（如果有） -->
            <div v-if="judgeResult?.submission?.status !== 0 && judgeResult?.submission?.errorMessage"
                 class="error-message mt-4">
              <div class="error-title">错误信息：</div>
              <pre class="error-content">{{ judgeResult?.submission?.errorMessage }}</pre>
            </div>

            <div class="mt-4 flex justify-center">
              <a-button type="primary" @click="viewJudgeDetail">
                <template #icon>
                  <EyeOutlined/>
                </template>
                查看评测详情
              </a-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-card>
</template>

<script>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import CodeMirror from 'codemirror';
import {
  CheckOutlined,
  RedoOutlined,
  SaveOutlined,
  EyeOutlined,
  QuestionCircleOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons-vue';

import { useProblemJudgement } from '@/composables/useProblemJudgement';
import { getJudgeResult, submitJudge } from "@/api/hoj-judge.js";
import { useUntil } from "@/composables/useUntil.js";

// codemirror 样式
import "codemirror/mode/clike/clike.js";  // Java/C++ support
import "codemirror/mode/python/python.js"; // Python support
import 'codemirror/lib/codemirror.css';    // 核心样式
import 'codemirror/theme/eclipse.css';    // 主题样式
import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/addon/hint/show-hint.js';
import 'codemirror/addon/edit/matchbrackets.js';  // 括号匹配
import 'codemirror/addon/edit/closebrackets.js';  // 自动闭合括号
import 'codemirror/addon/display/autorefresh.js'; // 自动刷新
import 'codemirror/addon/selection/active-line.js'; // 高亮当前行
import 'codemirror/addon/fold/foldcode.js';       // 代码折叠
import 'codemirror/addon/fold/foldgutter.js';     // 折叠槽
import 'codemirror/addon/fold/brace-fold.js';     // 大括号折叠
import 'codemirror/addon/fold/comment-fold.js';   // 注释折叠
import 'codemirror/addon/fold/foldgutter.css';    // 折叠样式
import 'codemirror/addon/lint/lint.js';           // 错误检查基础支持
import 'codemirror/addon/lint/lint.css';          // 错误检查样式

export default {
  name: 'CodeEditor',
  components: {
    CheckOutlined,
    InfoCircleOutlined,
    RedoOutlined,
    SaveOutlined,
    EyeOutlined,
    QuestionCircleOutlined
  },
  props: {
    problem: {
      type: Object,
      required: true
    },
    validLanguages: { // TODO 这个参数应该也放进来，并且
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    const router = useRouter();
    const selectedLanguage = ref('Java');
    const code = ref('');
    const isTestsubmitting = ref(false);
    const isSubmitsubmitting = ref(false);
    const showTestResult = ref(false);
    const showSubmitResult = ref(false);
    const judgeResult = ref(null);
    const submissionResult = ref({});
    const { submitProblemTest } = useProblemJudgement();
    const { waitForMilliseconds } = useUntil();
    const cmOptions = ref({
      mode: 'text/x-java',
      theme: 'eclipse',
      lineNumbers: true,
      indentUnit: 4,
      smartIndent: true,
      matchBrackets: true,      // 括号匹配高亮
      autoCloseBrackets: true,  // 自动闭合括号
      styleActiveLine: true,    // 高亮当前行
      foldGutter: true,         // 启用代码折叠
      autoRefresh: true,        // 实时刷新
      gutters: [
        'CodeMirror-linenumbers',
        'CodeMirror-foldgutter'
      ],
      extraKeys: {
        "Tab": "defaultTab",
        "Ctrl-Q": function (cm) {
          cm.foldCode(cm.getCursor());
        }
      }
    });
    
    // 编辑器实例
    const editorInstance = ref(null);
    // 错误标记数组
    const codeMarkers = ref([]);

    // 处理测试提交
    const handleTest = async () => {
      if (!code.value.trim()) {
        message.error('请输入代码');
        return;
      }

      isTestsubmitting.value = true;
      try {
        const data = {
          "pid": props.problem.id,
          "language": selectedLanguage.value,
          "code": code.value,
          "type": "public",
          "userInput": props.problem.exampleData?.[0]?.input || "",
          "expectedOutput": props.problem.exampleData?.[0]?.output || "",
          "mode": cmOptions.value.mode,
          "isRemoteJudge": true
        };

        const result = await submitProblemTest(data);
        
        // 处理返回结果
        submissionResult.value = {
          id: Date.now(),
          status: getStatusFromResult(result.status),
          executionTime: `${result.time}ms`,
          memoryUsage: `${(result.memory / 1024).toFixed(2)}MB`,
          submitTime: new Date().toLocaleString(),
          language: selectedLanguage.value,
          userInput: result.userInput,
          userOutput: result.userOutput,
          expectedOutput: result.expectedOutput,
          stderr: result.stderr,
          testcases: [
            {
              input: result.userInput,
              expectedOutput: result.expectedOutput,
              actualOutput: result.userOutput,
              status: getStatusFromResult(result.status),
              executionTime: `${result.time}ms`,
              memoryUsage: `${(result.memory / 1024).toFixed(2)}MB`
            }
          ],
          files: [
            {
              name: `提交详情_${Date.now()}.txt`,
              type: 'report',
              size: result.stderr ? result.stderr.length * 2 : 1024,
              url: `report_${Date.now()}`,
              content: getReportContent(result)
            }
          ]
        };

        showTestResult.value = true;
        message.success('测试成功');
      } catch (error) {
        message.error('测试失败：' + (error.message || '未知错误'));
      } finally {
        isTestsubmitting.value = false;
      }
    };

    // 处理正式提交
    const handleSubmit = async () => {
      if (!code.value.trim()) {
        message.error('请输入代码');
        return;
      }

      isSubmitsubmitting.value = true;
      try {
        const data = {
          "pid": props.problem.problemId,
          "rawId": props.problem.id,
          "problemTitle": props.problem.title,
          "code": code.value,
          "language": selectedLanguage.value
        };
        
        const submitResp = await submitJudge(data);
        message.success('提交成功，正在获取评测结果...');
        await waitForMilliseconds(1000);

        const judgeResponse = await getJudgeResult(submitResp.data.submitId);
        judgeResult.value = judgeResponse.data;

        // 显示提交结果 Drawer
        showSubmitResult.value = true;

        // 隐藏测试结果 Drawer（如果显示的话）
        showTestResult.value = false;
      } catch (error) {
        message.error('提交失败：' + (error.message || '未知错误'));
      } finally {
        isSubmitsubmitting.value = false;
      }
    };

    // 保存代码到 localStorage
    const handleSave = () => {
      const key = `oj_problem_${props.problem.problemId}_${selectedLanguage.value}`;
      localStorage.setItem(key, code.value);
      message.success('代码已保存');
    };

    // 重置代码
    const handleReset = () => {
      const key = `oj_problem_${props.problem.problemId}_${selectedLanguage.value}`;
      localStorage.removeItem(key);
      code.value = '';
      showTestResult.value = false;
      showSubmitResult.value = false;
      loadSavedCode(); // 重置为模板代码
      message.info('代码已重置');
    };

    // 加载保存的代码
    const loadSavedCode = () => {
      const key = `oj_problem_${props.problem.problemId}_${selectedLanguage.value}`;
      const savedCode = localStorage.getItem(key);
      if (savedCode) {
        code.value = savedCode;
        message.info('已加载上次保存的代码');
      } else {
        // 如果没有保存的代码，使用模板
        const templates = {
          Java: `class Main {
    public static void main(String[] args) {
        // 在这里写入你的代码
        System.out.println("");
    }
}`,
          python: `class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        // 在这里写入你的代码
        return [0, 0]`,
          cpp: `class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // 在这里写入你的代码
        return {0, 0};
    }
};`
        };
        code.value = templates[selectedLanguage.value] || templates.Java;
      }
    };

    // 更新编辑器模式
    const updateCodeMirrorMode = () => {
      switch (selectedLanguage.value) {
        case 'Java':
          cmOptions.value.mode = 'text/x-java';
          break;
        case 'cpp':
          cmOptions.value.mode = 'text/x-c++src';
          break;
        case 'python':
          cmOptions.value.mode = 'text/x-python';
          break;
        default:
          cmOptions.value.mode = 'text/x-java';
      }

      // 强制刷新以应用新模式和设置
      setTimeout(() => {
        if (editorInstance.value) {
          const cm = editorInstance.value;
          cm.setOption('mode', cmOptions.value.mode);
          cm.setOption('lint', true); // 重新启用lint
          cm.refresh();
          cm.performLint();
        }
      }, 100);
    };

    // 在挂载时执行
    onMounted(() => {
      loadSavedCode();
      updateCodeMirrorMode();
    });

    // 监听语言变化
    watch(selectedLanguage, () => {
      loadSavedCode();
      updateCodeMirrorMode();
    });

    // 处理编辑器容器的点击事件
    const handleEditorContainerClick = (event) => {
      if (showTestResult.value) {
        showTestResult.value = false;
      }
      if (showSubmitResult.value) {
        showSubmitResult.value = false;
      }
    };

    // 编辑器值改变事件
    const change = (val) => {
      code.value = val;

      // 如果有编辑器实例，检查括号错误和其他语法错误
      if (editorInstance.value) {
        checkCodeErrors(val, editorInstance.value);
      }
    };

    // 编辑器准备就绪事件
    const onCmReady = (cm) => {
      // 存储CodeMirror实例以便后续使用
      editorInstance.value = cm;

      // 配置CodeMirror实例
      cm.setOption("matchBrackets", true);
      cm.setOption("autoCloseBrackets", true);

      // 初始化时检查代码错误
      checkCodeErrors(code.value, cm);

      // 刷新以确保正确渲染
      setTimeout(() => {
        cm.refresh();
        cm.focus();
      }, 100);
    };

    // 综合检查代码错误
    const checkCodeErrors = (text, cm) => {
      // 清除所有现有标记
      if (codeMarkers.value.length) {
        codeMarkers.value.forEach(marker => marker.clear());
        codeMarkers.value = [];
      }

      // 检查括号错误
      checkBracketErrors(text, cm);

      // 检查分号错误（针对Java和C++）
      if (['text/x-java', 'text/x-c++src'].includes(cmOptions.value.mode)) {
        checkSemicolonErrors(text, cm);
      }

      // 检查缩进错误
      checkIndentationErrors(text, cm);
    };

    // 检查括号错误
    const checkBracketErrors = (text, cm) => {
      const brackets = {
        '(': ')',
        '{': '}',
        '[': ']'
      };

      const stack = [];

      // 查找不匹配的括号
      for (let i = 0; i < text.length; i++) {
        const char = text.charAt(i);
        const pos = cm ? cm.posFromIndex(i) : CodeMirror.Pos(0, i);

        if (brackets[char]) {
          stack.push({char, pos});
        } else if (Object.values(brackets).includes(char)) {
          const expected = stack.pop();
          if (!expected || brackets[expected.char] !== char) {
            const marker = cm.markText(
                pos,
                {line: pos.line, ch: pos.ch + 1},
                {
                  className: 'syntax-error',
                  title: `不匹配的括号: '${char}'`,
                  css: "text-decoration: underline wavy red; background-color: rgba(255,0,0,0.1);"
                }
            );
            codeMarkers.value.push(marker);
          }
        }
      }

      // 检查未闭合的括号
      stack.forEach(item => {
        const marker = cm.markText(
            item.pos,
            {line: item.pos.line, ch: item.pos.ch + 1},
            {
              className: 'syntax-error',
              title: `未闭合的括号: '${item.char}'`,
              css: "text-decoration: underline wavy red; background-color: rgba(255,0,0,0.1);"
            }
        );
        codeMarkers.value.push(marker);
      });
    };

    // 检查分号错误（针对Java和C++）
    const checkSemicolonErrors = (text, cm) => {
      const lines = text.split('\n');

      lines.forEach((line, i) => {
        // 忽略注释、空行和大括号行
        if (line.trim().startsWith('//') || !line.trim() || line.trim() === '{' || line.trim() === '}') {
          return;
        }

        // 检查行是否以分号结束
        const trimmed = line.trimEnd();
        if (trimmed && !trimmed.endsWith(';') && !trimmed.endsWith('{')) {
          const lastChar = trimmed.length - 1;
          const marker = cm.markText(
              {line: i, ch: lastChar},
              {line: i, ch: lastChar + 1},
              {
                className: 'syntax-error',
                title: '可能缺少分号',
                css: "text-decoration: underline wavy orange; background-color: rgba(255,165,0,0.1);"
              }
          );
          codeMarkers.value.push(marker);
        }
      });
    };

    // 检查缩进错误
    const checkIndentationErrors = (text, cm) => {
      const lines = text.split('\n');
      let expectedIndent = 0;
      const indentSize = 4; // 默认缩进大小

      lines.forEach((line, i) => {
        const trimmed = line.trim();
        if (!trimmed) return; // 忽略空行

        // 计算当前行的缩进
        const indent = line.length - line.trimStart().length;

        // 检查大括号以更新预期缩进
        if (trimmed.includes('{')) {
          // 当前行有开括号，下一行应该增加缩进
          if (i < lines.length - 1) {
            const nextLine = lines[i + 1].trim();
            if (nextLine && !nextLine.startsWith('}')) {
              expectedIndent += indentSize;
            }
          }
        } else if (trimmed.startsWith('}')) {
          // 当前行有闭括号，应该减少缩进
          expectedIndent = Math.max(0, expectedIndent - indentSize);
        }

        // 检查当前行的缩进是否符合预期
        if (trimmed && !trimmed.startsWith('//') && Math.abs(indent - expectedIndent) > 0) {
          const marker = cm.markText(
              {line: i, ch: 0},
              {line: i, ch: Math.min(indent, 10)},
              {
                className: 'indentation-error',
                title: '缩进可能不正确',
                css: "background-color: rgba(255,255,0,0.2);"
              }
          );
          codeMarkers.value.push(marker);
        }
      });
    };

    // 根据状态码获取状态文本
    const getStatusFromResult = (status) => {
      switch (status) {
        case 0:
          return 'passed';
        case -1:
          return 'wrong_answer';
        case -2:
          return 'compile_error';
        case -3:
          return 'runtime_error';
        case -4:
          return 'time_limit_exceeded';
        case -5:
          return 'memory_limit_exceeded';
        default:
          return 'failed';
      }
    };

    // 生成报告内容
    const getReportContent = (result) => {
      let report = `提交详情报告\n==================\n\n`;
      report += `提交时间：${new Date().toLocaleString()}\n`;
      report += `语言：${selectedLanguage.value}\n`;

      // 执行状态
      const statusMap = {
        0: '通过',
        '-1': '答案错误',
        '-2': '编译错误',
        '-3': '运行时错误',
        '-4': '超时',
        '-5': '内存超限'
      };

      report += `执行结果：${statusMap[result.status] || '失败'}\n`;
      report += `执行用时：${result.time}ms\n`;
      report += `内存消耗：${(result.memory / 1024).toFixed(2)}MB\n\n`;

      if (result.status === -2 && result.stderr) {
        report += `编译错误信息：\n${result.stderr}\n\n`;
      } else {
        report += `输入：\n${result.userInput || '无'}\n\n`;
        report += `期望输出：\n${result.expectedOutput || '无'}\n\n`;
        report += `实际输出：\n${result.userOutput || '无'}\n\n`;

        if (result.stderr) {
          report += `错误输出：\n${result.stderr}\n\n`;
        }
      }

      return report;
    };

    // 获取状态标签
    const getStatusTag = (status) => {
      switch (status) {
        case 'passed':
          return {color: 'success', text: '通过'};
        case 'wrong_answer':
          return {color: 'error', text: '答案错误'};
        case 'compile_error':
          return {color: 'warning', text: '编译错误'};
        case 'runtime_error':
          return {color: 'error', text: '运行时错误'};
        case 'time_limit_exceeded':
          return {color: 'warning', text: '超时'};
        case 'memory_limit_exceeded':
          return {color: 'warning', text: '内存超限'};
        case 'failed':
        default:
          return {color: 'error', text: '失败'};
      }
    };

    // 获取评测状态文本
    const getJudgeStatusText = (status) => {
      switch (status) {
        case 0:
          return 'Accepted';
        case -1:
          return 'Wrong Answer';
        case -2:
          return 'Compile Error';
        case -3:
          return 'Runtime Error';
        case -4:
          return 'Time Limit Exceeded';
        case -5:
          return 'Memory Limit Exceeded';
        case -999:
          return 'Failed';
        default:
          return '未知';
      }
    };

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString();
    };

    // 格式化内存
    const formatMemory = (memory) => {
      if (!memory) return '0KB';
      return (memory / 1024).toFixed(2) + 'MB';
    };

    // 跳转到评测详情页
    const viewJudgeDetail = () => {
      if (judgeResult.value?.submission?.submitId) {
        router.push(`/oj/judge-submit/${judgeResult.value.submission.submitId}`);
      } else {
        message.error('无法获取评测ID');
      }
    };

    return {
      selectedLanguage,
      code,
      cmOptions,
      isTestsubmitting,
      isSubmitsubmitting,
      showTestResult,
      showSubmitResult,
      submissionResult,
      judgeResult,
      handleTest,
      handleSubmit,
      handleSave,
      handleReset,
      handleEditorContainerClick,
      change,
      onCmReady,
      getStatusTag,
      getJudgeStatusText,
      formatDate,
      formatMemory,
      viewJudgeDetail,
      checkCodeErrors,
      editorInstance,
      codeMarkers
    };
  }
};
</script>

<style scoped>
/* 编辑器相关样式 */
.editor-card {
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.editor-actions {
  display: flex;
  gap: 8px;
}

.editor-actions .ant-btn {
  display: flex;
  align-items: center;
}

.editor-container {
  position: relative;
  height: 620px;
  overflow: hidden;
}

.result-drawer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-top: 1px solid #f0f0f0;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.15);
  z-index: 10;
  animation: slideUp 0.3s ease;
  border: 1px solid #f0f0f0;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.result-drawer-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.result-drawer-body {
  padding: 16px 24px;
  height: calc(100% - 56px);
  overflow-y: auto;
}

.result-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.result-content {
  font-size: 14px;
}

.result-item {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.result-item .label {
  color: #8c8c8c;
  margin-right: 8px;
}

.error-message {
  margin-top: 12px;
  padding: 12px;
  background: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  color: #ff4d4f;
}

.error-title {
  font-weight: 500;
  margin-bottom: 8px;
}

.error-content {
  font-family: monospace;
  white-space: pre-wrap;
  background: #ffe8e6;
  padding: 8px;
  border-radius: 4px;
  margin: 0;
  overflow-x: auto;
}

.success-message {
  margin-top: 12px;
  padding: 12px;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 4px;
  color: #52c41a;
}

.success-title {
  font-weight: 500;
  margin-bottom: 12px;
}

.testcase-result {
  margin-top: 12px;
  padding: 12px;
  background: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 4px;
}

.testcase-header {
  font-weight: 500;
  margin-bottom: 12px;
}

.testcase-item {
  margin-bottom: 12px;
}

.testcase-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.testcase-content {
  font-family: monospace;
  background: #fafafa;
  padding: 8px;
  border-radius: 4px;
  margin: 0;
  white-space: pre-wrap;
  overflow-x: auto;
}

.yellow-btn {
  background-color: #faad14; /* 黄色 */
  color: #fff;
  border-color: #faad14;
}

.yellow-btn:hover {
  background-color: #fca326;
  border-color: #fca326;
  color: #fff;
}

.submit-result-drawer {
  background-color: #f9f9f9;
}

.success-header {
  background-color: #d9f7be;
  border-bottom-color: #b7eb8f;
}

.error-header {
  background-color: #ffccc7;
  border-bottom-color: #ffa39e;
}

.success-body {
  background-color: #f6ffed;
}

.error-body {
  background-color: #fff2f0;
}

.mt-4 {
  margin-top: 1rem;
}

.flex {
  display: flex;
}

.justify-center {
  justify-content: center;
}

/* CodeMirror错误提示样式 */
:deep(.syntax-error) {
  text-decoration: underline wavy red !important;
  background-color: rgba(255, 0, 0, 0.1) !important;
  cursor: pointer !important;
}

:deep(.indentation-error) {
  background-color: rgba(255, 255, 0, 0.2) !important;
  cursor: pointer !important;
}

:deep(.CodeMirror) {
  font-family: 'JetBrains Mono', 'Fira Code', Menlo, Monaco, 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.CodeMirror-matchingbracket) {
  background-color: rgba(0, 255, 0, 0.1) !important;
  color: inherit !important;
  font-weight: bold;
}

:deep(.CodeMirror-nonmatchingbracket) {
  background-color: rgba(255, 0, 0, 0.2) !important;
  color: red !important;
}
</style> 